<template>
  <div>
    <div class="canvas">
      <canvas :id="id" :width="width" :height="height"></canvas>
      <div class="devices-btn" v-if="floor">
        <van-button>
          <van-icon name="arrow-up" />
        </van-button>
        <van-button>1F</van-button>
        <van-button>2F</van-button>
        <van-button>3F</van-button>
        <van-button>4F</van-button>
        <van-button>5F</van-button>
        <van-button>
          <van-icon name="arrow-down" /></van-button>
      </div>
      <div class="devices-btn-right" v-if="plus">
        <van-button @click="zoomIn">
          +
        </van-button>
        <van-button>{{parseInt( scale*100) }}</van-button>
        <van-button @click="zoomOut">
          -
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import floorImg  from '../assets/floor.png';
import dxq  from '../assets/dxq.png';

import tx  from '../assets/tx.png';
import hlq  from '../assets/hlq.png';
import { Dialog } from 'vant'
import testApi from '@/api/test.js'

import axios from 'axios';
export default {
  name: 'convasImg',
  components:{
    dxq, 
    tx, 
    hlq
  },
  props:{
    id:{
      type:String,
      default:'canvasId'
    },
    floor:{
      type: Boolean,
      default:false
    },
    plus:{
      type:Boolean,
      default:false,
    },
    width:{
      type:Number
    },
    height:{
      type:Number
    },
    activeImg:{
      type:String
    }
  },
  data() {
    return {
      active: 0,
      value: '',
      canvas:null,
      ctx:null,
      startX:0,
      startY:0,
      endX:0,
      endY:0,
      dragable:false,
      offsetX:0,
      offsetY:0,
      singleClick:true,
      img:null,
      timer:null,
      showPopup:false,
      selectedOption: {},
      showSfxt:false,
      options: [
        { text: '选项1', value: '1' },
        { text: '选项2', value: '2' },
        { text: '选项3', value: '3' }
      ],
      showPopups:false,
      selectType:'',
      scale:1,
      photo:'',
      pointList:[],
      initialDistance:0,
      scaleFactor:1,
      iconEdit:false,
      iconIndex:-1,
      detailData:{},
      resultACtion:'',
    };
  },
  created(){
    this.$nextTick(()=>{
      this.initCanvas();
    },2000)
  },
  methods: {
    showPicker() {
      this.showPopups = true;
    },
    onPickerConfirm(value) {
      this.selectedValue = value[0];
      this.showPopups = false;
    },
    onPickerCancel() {
      this.showPopups = false;
    },
    
    /**
     * @param {*} 初始化画布
     */
    initCanvas(){
      this.canvas = document.getElementById(this.id);
      this.ctx = this.canvas.getContext('2d');

      let h1 = document.querySelector('.add-top').clientHeight;
      let h2 = document.querySelector('.van-nav-bar').clientHeight;
      this.canvas.width = this.width;
      this.canvas.height = this.height;
      this.canvas.addEventListener('touchstart', this.downFun,{
        passive: true
      })
      this.canvas.addEventListener('touchmove', this.moveFun,{
        passive: true
      })
      this.canvas.addEventListener('touchend', this.endFun,{
        passive: true
      })
      
      this.canvas.addEventListener('oncontextmenu', this.menuFun);
      this.drawImg();
    },
    
    /**
     * @param {*} 绘制图纸
     */
    drawImg(){
      this.img = new Image();
      this.img.src = floorImg;
      this.img.onload=()=>{
        requestAnimationFrame(this.animate);
      }
    },
    animate(){
        let width = this.img.width;
        let height = this.img.height;
        let radio = Math.max( this.canvas.width/this.img.width , this.canvas.height/this.img.height);
        
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(
          this.img,
          -this.offsetX,
          -this.offsetY,
          width*radio*this.scale,
          height*radio*this.scale
        );
        this.img.width = width*radio*this.scale;
        this.img.height = height*radio*this.scale;
        if(this.pointList.length > 0){
          this.drawIconHistory();
        }
    },
    
    /**
     * @param {*} 第一次点击
     */
    downFun(e){
      if (e.touches.length === 2) { // 双指触摸
          this.initialDistance = Math.hypot(
              e.touches[0].pageX - e.touches[1].pageX, 
              e.touches[0].pageY - e.touches[1].pageY
          );
          return;
      }
      this.dragable=true;
      this.timer = new Date().getTime();
      this.startX = e.changedTouches[0].clientX + this.offsetX;
      this.startY = e.changedTouches[0].clientY + this.offsetY;
    },
    /**
     * 
     * @param {*} 开始滑动
     */
    moveFun(e){
      if (e.touches.length === 2) { // 双指触摸并移动
          var currentDistance = Math.hypot(
              e.touches[0].pageX - e.touches[1].pageX, 
              e.touches[0].pageY - e.touches[1].pageY
          );
          var scale = currentDistance / this.initialDistance;
          this.scaleFactor *= scale;
          initialDistance = currentDistance;
  
          // 清除画布并重新绘制
          this.ctx.clearRect(0, 0, canvas.width, canvas.height);
          this.ctx.save();
          this.ctx.scale(this.scaleFactor, this.scaleFactor);
          this.drawImg();
          // 在这里绘制你的内容
          this.ctx.restore();
          return;
      }
      if(this.dragable){
        this.offsetX =  this.startX - e.changedTouches[0].clientX;
        this.offsetY =  this.startY - e.changedTouches[0].clientY;
        this.moveImg(e);
        
        // this.drawImg();
        // this.ctx.translate(this.offsetX,this.offsetY);

      }
    },
    /**
     * 
     * @param {*} 结束滑动
     */
    endFun(e){
      this.dragable = false;
      this.endX = e.changedTouches[0].clientX;
      this.endY = e.changedTouches[0].clientY;
      if((new Date().getTime()) - this.timer <200){
        if(!this.activeImg){
          return;
        }
        let h1 = document.querySelector('.add-top').clientHeight;
        let h2 = document.querySelector('.van-nav-bar').clientHeight;
        let imgs = new Image();
        // imgs.src = this.activeImg;
        imgs.src = this.activeImg;
        console.log(111, imgs.src)
        let h = 20/imgs.height;
        let str = {
          img: imgs,
          x: e.changedTouches[0].clientX - h*imgs.width/2 + this.offsetX,
          y: e.changedTouches[0].clientY - h1- h2 - h*imgs.height - h*imgs.height/2 + this.offsetY,
          w:h*imgs.width,
          h:h*imgs.height
        }
        let getRect = this.calpoint(JSON.parse(JSON.stringify(this.pointList)), e);
        this.iconEdit = false;
        this.iconIndex = -1;
        if(getRect!==-1){
          //如果当前点已经添加设备，则弹出设备删除设备提示
          this.iconEdit = true;
          //记录点击的哪个点
          this.iconIndex = getRect;
        }else{
          this.pointList.push(str);
          this.iconIndex = this.pointList.length - 1;
        }
        this.$emit('openPoup');
        this.$emit('getPoint', {x:e.changedTouches[0].clientX - h*imgs.width/2 + this.offsetX,y:e.changedTouches[0].clientY - h1- h2 - h*imgs.height - h*imgs.height/2 + this.offsetY})
        this.drawIcon();
      }

    },
    convertUrlToBase64(url) {
      try {
        const response = fetch(url);
        const blob = response.blob();
        const reader = new FileReader();
        reader.onload = e => {
          this.imageUrl = e.target.result;
        };
        reader.readAsDataURL(blob);
      } catch (error) {
        console.error('Error converting URL to Base64:', error);
      }
    },
    /**
     * 计算是否点中图标
     */
    calpoint(str, e){
        if(str.length > 0){
          let h1 = document.querySelector('.add-top').clientHeight;
          let h2 = document.querySelector('.van-nav-bar').clientHeight;
          let imgs = new Image();
          imgs.src = this.activeImg;
          let h = 20/imgs.height
          for(var i = 0;i < str.length; i++){
            let cx = e.changedTouches[0].clientX,cy = e.changedTouches[0].clientY- h1- h2 - h*imgs.height - h*imgs.height/2 + this.offsetY;
            if(  
              cx < str[i].x + h*imgs.width && 
              cx > str[i].x - h*imgs.width && 
              cy < str[i].y + h*imgs.height && 
              cy > str[i].y - h*imgs.height){

              return i;
            }
          }
          return -1;
        }else{
          return -1;
        }
    },
    drawIcon(){
      this.pointList.map(m=>{

        this.ctx.drawImage(m.img, m.x - this.offsetX, m.y - this.offsetY, m.w,  m.h);
      })
    },
    /**
     * 拖动和缩放时候触发重新画点
     */
    drawIconHistory(){
      let radio = Math.max( this.canvas.width/this.img.width , this.canvas.height/this.img.height);
      this.pointList.map(m=>{
        this.ctx.drawImage(m.img, m.x/radio - this.offsetX, m.y/radio - this.offsetY, m.w,  m.h);
        return m;
      })
    },
    menuFun(e){
      e.preventDefault();
      return false;
    },
    clearCanvas(){
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    onSearch() {
    },
    onCancel() {
      this.showPopup = false;
    },
    onChange(){

    },
    selectOption(option) {
      if(this.selectType==1){
        this.selectedOption.text1 = option.text;
        this.selectOption.value1 = option.value;
      }else if(this.selectType==2){
        this.selectedOption.text2 = option.text;
        this.selectOption.value2 = option.value;

      }else{
        this.selectedOption.text3 = option.text;
        this.selectOption.value3 = option.value;

      }
      this.showSfxt = false;
    },
    openPop(type){
      this.selectType = type;
      if(type)
      this.showSfxt = true
    },
    zoomIn(){
      this.scale += 0.1;
      this.drawImg();
    },
    zoomOut(){
      this.scale -= 0.1;
      this.drawImg();
     
    },
    moveImg(e){
      this.img = new Image();
      this.img.src = floorImg;
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      let radio = Math.max( this.canvas.width/this.img.width , this.canvas.height/this.img.height);
      this.ctx.drawImage(this.img, e.changedTouches[0].clientX - this.startX,  e.changedTouches[0].clientY - this.startY, this.img.width*radio*this.scale, this.img.height*radio*this.scale);
      this.img.width = this.img.width*radio*this.scale;
      this.img.height = this.img.height*radio*this.scale;
      this.drawIconHistory();
    },
    /**
     * 删除设备
    */
    delDevice(){
      Dialog.confirm({
        title: "提示",
        message: "是否确定删除该点位?"
      }).then(() => {
        this.pointList.splice(this.iconIndex, 1);
        this.showPopup = false;
        this.iconIndex = -1;
        this.drawImg();
      }).catch(() => {});
    },
    /**
     * idsId 室分系统id
     * manufactureCompany 生产企业
     * address 安装地址
     * latitude 经度
     * longitude 维度
     * onlineStatus 在线状态
     * parentId 父级设备
     * installStatus 设备状态
     * equipmentType 设备分类
     * 
     * deviceType 设备类型
     * deviceName 设备名称
     * idsId 室分系统id
     * deviceResourceId 设备资源id
     * deviceNum 设备编码/设备运维id
     * drawingLocation 图片地址
     * deviceSn 设备SN码
     */
    save(){
      this.$emit('save', this.selectedOption )
     
    },
    
  },
};
</script>

<style scoped lang="less">
.content{
  user-select: none;
  overflow: hidden;
}
  .add-content{
    font-size: 16px;
  }

  .add-top{
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    margin: 10px;
  }
  .add-font{
    font-size: 16px;
    padding: 0 3px;
  }
  .img-font{
    text-align: center;
    font-size: 12px;
    padding: 3px 5px;
    width: 40px;
  }
  .img-font.active{
    box-shadow: 0 0 3px #000;
    background: rgba(0,0,0,0.1);
  }
  .canvas{
    /* border:1px solid red; */
    box-shadow: 0 0 3px #999;
    height: 100%;
    width: 100%;
    overflow: hidden;

  }
  .tips-bg{
    background: #fff;
    height: 50%;
    position: absolute;
    bottom: 0;
    width: 100%;
  }
  .tips-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin:10px;
  }
  .tips-bg-btn{
    display: flex;
  }
  .tips-btn{
    width: 100px;
    margin-right: 10px;
  }
  .devices-btn{
    position: fixed;
    bottom: 20px;
    left: 20px;
    display: flex;
    flex-direction:column;
    box-shadow: 0 0 3px rgba(0,0,0,0.3);
    border-top: 1px solid  rgba(0,0,0,0.3);
    border-radius: 10px;
    overflow: hidden;
    button{
      border: 1px solid rgba(0,0,0,0.3);
      border-radius: 0;
      border-top: none;
      &:first-child{
        height: 30px;
      }
      &:last-child{
        height: 30px;
      }
    }
    
  }
  .devices-btn-right{
    position: fixed;
    bottom: 20px;
    right: 20px;
    display: flex;
    flex-direction:column;
    box-shadow: 0 0 3px rgba(0,0,0,0.3);
    border-top: 1px solid  rgba(0,0,0,0.3);
    border-radius: 10px;
    overflow: hidden;
    button{
      border: 1px solid rgba(0,0,0,0.3);
      border-radius: 0;
      border-top: none;
      &:first-child{
        height: 30px;
      }
      &:last-child{
        height: 30px;
      }
    }
  }
  .display-flex{
    display: flex;
    justify-content: space-between;
  }
  .form-item{
    display: flex;
    justify-content: space-between;
    .van-icon-arrow-down:before{
      font-size: 16px;
      margin-right:20px;
    }
    .van-icon-scan, .van-icon-photograph{
      font-size: 16px;
      margin-right: 20px;
      margin-top: 10px;
    }
    &.start{
      justify-content: flex-start;
      .van-cell{
        width: 120px;
      }
    }
  }
  .device-img{
    img{
      height: 20px;
    }
  }
</style>